﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows;

namespace Games.Helper.Controls
{
    public class NumberTextBox : TextBox
    {
        public int Step {
            get { return (int)GetValue(StepProperty); }
            set { SetValue(StepProperty, value); }
        }

        public static readonly DependencyProperty StepProperty =
            DependencyProperty.Register("Step", typeof(int), typeof(NumberTextBox), new PropertyMetadata(1));

        public int Minimum {
            get { return (int)GetValue(MinimumProperty); }
            set { SetValue(MinimumProperty, value); }
        }
        public static readonly DependencyProperty MinimumProperty =
            DependencyProperty.Register("Minimum", typeof(int), typeof(NumberTextBox), new PropertyMetadata(0));

        static NumberTextBox()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(NumberTextBox), new FrameworkPropertyMetadata(typeof(NumberTextBox)));
        }

        public NumberTextBox()
        {
            InputMethod.SetIsInputMethodEnabled(this, false);
            this.PreviewTextInput += NumberTextBox_PreviewTextInput;
        }

        private void NumberTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            e.Handled = new Regex("[^0-9]+").IsMatch(e.Text);
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            Button PlusButton = (Button)this.Template.FindName("PlusButton", this);
            Button MinusButton = (Button)this.Template.FindName("MinusButton", this);

            PlusButton.Click += PlusButton_MouseLeftButtonDown;
            MinusButton.Click += MinusButton_MouseLeftButtonDown;
        }

        private void MinusButton_MouseLeftButtonDown(object sender, RoutedEventArgs e)
        {
            if (!String.IsNullOrEmpty(this.Text)) {
                this.Text = int.Parse(this.Text) - Step < Minimum ? Minimum + "" : int.Parse(this.Text) - Step + "";
                this.SelectionStart = this.Text.Length;
            } else {
                this.Text = Minimum + "";
                this.SelectionStart = this.Text.Length;
            }
        }

        private void PlusButton_MouseLeftButtonDown(object sender, RoutedEventArgs e)
        {
            if (!String.IsNullOrEmpty(this.Text)) {
                this.Text = int.Parse(this.Text) + Step + "";
                this.SelectionStart = this.Text.Length;
            } else {
                this.Text = Minimum + "";
                this.SelectionStart = this.Text.Length;
            }
        }
    }
}
